// 获取应用实例
const app = getApp()
import { date_time, formatDate } from '../../utils/util';
let innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.src = "/assets/ding.mp3";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0, // 盘点明细Id
    inventoryId: 0, // 盘点Id
    inventoryDetail: {
      Id: 0,
      FixedAssetsCheckId: 0,
      FixedAssetsInfoId: 0,
      OrganizationId: 0,
      ManageDepartmentId: 0,
      UserDepartmentId: 0,
      AssetsName: '',
      AssetsEncoding: '',
      AssetsCategoryId: 0,
      AssetsCategoryName: '',
      AssetsSpecificationAndModel: '',
      AssetsSupplierId: 0,
      AssetsManufacturer: '',
      Place: '',
      Unit: '',
      StartOn: '',
      AssetsSum: 0,
      Rate: 0,
      Tax: 0,
      InventoryUseState: 0,
      InventoryUserName: '',
      InventoryAmount: 0, // 盘点数量
      UserName: '',
      UseState: 0, // 使用状态
      UseStateName: '',
      CreatedOn: formatDate(new Date()),
      FileList: [], // 现场图片
      UseStates: [], // 状态
    }, // 库存信息
    showStates: false, // 显示状态选择框
    showStartOn: false, // 显示日期选择框
    showOrg: false, // 显示单位选择框
    showDep: false, // 显示部门选择框
    showCategory: false, // 显示资产类型选择框
    thumbUrl: '/assets/box.png', // 卡片默认图片
    UseStateIndex: 0, // 使用状态
    depIndex: 0, // 部门
    minDate: new Date(new Date().setMonth(new Date().getMonth() - 6)).getTime(),
    maxDate: new Date(new Date().setMonth(new Date().getMonth() + 6)).getTime(),
    defaultDate: new Date().getTime(),
    orgMainActiveIndex: 0,
    orgActiveId: null,
    orgItems: [],
    depItems: [],
    depName: '', // 操作的部门名称
    categoryMainActiveIndex: 0,
    categoryActiveId: null,
    categoryItems: [],
    categoryValue: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!options) return;
    const _this = this;
    const { id = 0, inventoryId = 0, opt = 'add' } = options;
    // 盘点明细
    app.ajax({
      url: 'ERP/GetMaterialsInventory',
      data: { id, inventoryId, showData: true },
      verifyToken: true,
      success(data) {
        if (data.result) {
          const inventoryDetail = data.inventory || {};
          if (inventoryDetail.StartOn) {
            inventoryDetail.StartOn = date_time(inventoryDetail.StartOn);
          }
          if (inventoryDetail.CreatedOn) {
            inventoryDetail.CreatedOn = date_time(inventoryDetail.CreatedOn);
          }
          _this.setData({ inventoryDetail });
          _this.getOrgData(data.inventory.Organizations);
          _this.getDepData(data.inventory.Departments, data.inventory.OrganizationId);
          _this.getCategoryData(data.inventory.Categorys);
        }
        else {
          app.showNotify(data.msg);
          wx.navigateBack({
            delta: 0,
          })
          return;
        }
      }
    });
    _this.setData({ id, inventoryId });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  stop() {
    console.log("进入后台");
  },

  done(e) {
    console.log("初始化完成", e);
  },

  // 输入框值变化
  onFieldChange(e) {
    const { detail, target: { id, dataset: { length } } } = e;
    const { inventoryDetail } = this.data;
    if (length > 0 && detail.length > length) {
      inventoryDetail[id] = detail.substring(0, length - 1);
    }
    else {
      inventoryDetail[id] = detail;
    }
    if (id === 'InventoryAmount' || id === 'AssetsPrice') {
      inventoryDetail.AssetsSum = (inventoryDetail.AssetsPrice * inventoryDetail.InventoryAmount).toFixed(2) * 1;
    }
    this.setData({ inventoryDetail });
  },

  // input值变化
  onInputChange(e) {
    const { detail: { value }, target: { id, dataset: { length } } } = e;
    const { inventoryDetail } = this.data;
    if (length > 0 && value.length > length) {
      inventoryDetail[id] = value.substring(0, length - 1);
    }
    else {
      inventoryDetail[id] = value;
    }
    this.setData({ inventoryDetail });
  },

  // 显示状态选择框
  showStates(e) {
    const { inventoryDetail: { InventoryUseState, UseState, UseStates } } = this.data;
    this.setData({ showStates: true, UseStateIndex: UseStates.findIndex(m => m.key * 1 === (InventoryUseState > 0 ? InventoryUseState : UseState)) || 0 });
  },

  closeStates() {
    this.setData({ showStates: false });
  },

  confirmStates(e) {
    const { detail: { value: { key, value } } } = e;
    const { inventoryDetail } = this.data;
    inventoryDetail.InventoryUseState = key * 1;
    inventoryDetail.UseStateName = value;
    inventoryDetail.InventoryUseStateName = value;
    this.setData({ inventoryDetail, showStates: false });
  },

  // 显示单位选择框
  showOrg(e) {
    this.setData({ showOrg: true });
  },

  closeOrg() {
    this.setData({ showOrg: false });
  },

  // 显示使用部门选择框
  showDep(e) {
    const { inventoryDetail: { UserDepartmentId }, depItems } = this.data;
    this.setData({ showDep: true, depName: 'UserDepartment', depIndex: depItems.findIndex(m => m.key * 1 === UserDepartmentId * 1) || 0 });
  },

  // 显示管理部门选择框
  showMDep(e) {
    const { inventoryDetail: { ManageDepartmentId }, depItems } = this.data;
    this.setData({ showDep: true, depName: 'ManageDepartment', depIndex: depItems.findIndex(m => m.key * 1 === ManageDepartmentId * 1) || 0 });
  },

  closeDep() {
    this.setData({ showDep: false });
  },

  confirmDep(e) {
    const { detail: { value: { key, value } } } = e;
    const { inventoryDetail, depName } = this.data;
    inventoryDetail[`${depName}Id`] = key * 1;
    inventoryDetail[`${depName}Name`] = value;
    // 默认管理部门与使用部门相同
    if (depName === 'UserDepartment' && inventoryDetail.ManageDepartmentId <= 0) {
      inventoryDetail.ManageDepartmentId = inventoryDetail.UserDepartmentId;
      inventoryDetail.ManageDepartmentName = inventoryDetail.UserDepartmentName;
    }
    this.setData({ inventoryDetail, showDep: false });
  },

  // 显示类型择框
  showCategory(e) {
    const { inventoryDetail: { FixedAssetsInfoId } } = this.data;
    // 源资产不允许变更资产名称
    if (FixedAssetsInfoId > 0) return;
    this.setData({ showCategory: true });
  },

  closeCategory() {
    this.setData({ showCategory: false });
  },

  showStartOn(e) {
    const { inventoryDetail: { StartOn } } = this.data;
    if (StartOn) {
      const defaultDate = new Date(StartOn).getTime();
      const minDate = new Date(new Date(StartOn).setMonth(new Date(StartOn).getMonth() - 6)).getTime();
      const maxDate = new Date(new Date(StartOn).setMonth(new Date(StartOn).getMonth() + 6)).getTime();
      this.setData({ showStartOn: true, defaultDate, minDate, maxDate });
    }
    else {
      const defaultDate = new Date().getTime();
      const minDate = new Date(new Date().setMonth(new Date().getMonth() - 6)).getTime();
      const maxDate = new Date(new Date().setMonth(new Date().getMonth() + 6)).getTime();
      this.setData({ showStartOn: true, defaultDate, minDate, maxDate });
    }
  },

  closeStartOn() {
    this.setData({ showStartOn: false });
  },

  confirmStartOn(e) {
    const { inventoryDetail } = this.data;
    inventoryDetail.StartOn = formatDate(e.detail);
    this.setData({
      showStartOn: false,
      inventoryDetail,
    });
  },

  readFile(e) {
    const { detail: { name, index, file } } = e;
    const { inventoryDetail } = this.data;
    inventoryDetail[name].push(file);
    this.setData({ inventoryDetail });
  },

  deleteFile(e) {
    const { detail: { name, index } } = e;
    const { inventoryDetail } = this.data;
    inventoryDetail[name].splice(index, 1);
    inventoryDetail.PictureId = 0; // 删除后设置为0，后台接收后清除旧图片
    this.setData({ inventoryDetail });
  },

  savePD(e) {
    const _this = this;
    const { inventoryDetail } = _this.data;
    const { FixedAssetsCheckId, PictureId, FileList } = inventoryDetail;
    if (FixedAssetsCheckId === 0) {
      app.showNotify('请刷新...');
      return;
    }; // 必须有盘点Id
    if (!inventoryDetail.AssetsEncoding || !inventoryDetail.AssetsName) {
      app.showNotify('资产名称、资产编码不能为空');
      return;
    };
    app.ajax({
      url: 'ERP/SaveMaterials', // 保存物资盘点信息
      data: inventoryDetail,
      timeout: 2000,
      again: false, // 重复调用
      verifyToken: true,
      success(data) {
        if (data.result) {
          if (data.fixedAssetsCheckDetailsId > 0 && PictureId === 0 && FileList && FileList.length > 0) {
            _this.uploadFile(inventoryDetail.FileList[0], data.fixedAssetsCheckDetailsId); // 上传图片
          }
          else {
            wx.navigateBack({
              delta: 0,
            });
          }
        }
        else {
          app.showNotify(data.msg || '保存失败');
        }
      }, fail(resp) {
        const { errMsg } = resp;
        if (errMsg && errMsg === 'request:fail timeout') { app.showNotify('请求超时'); }
      }
    });
  },

  uploadFile(file, id) {
    let _this = this;
    app.upload({
      name: 'imgfile',
      filePath: file.url,
      formData: { id },
      success(resp) {
        wx.navigateBack({
          delta: 0,
        });
      },
      fail(resp) {
        wx.navigateBack({
          delta: 0,
        });
      },
    });
  },

  getOrgData(d) {
    let data = [];
    d.map(m => {
      data.push({
        text: m.title,
        id: m.key,
        disabled: false,
        children: this.getOrgChildren(m),
      });
      return m.key;
    })
    this.setData({ orgItems: data });
  },

  getOrgChildren(d) {
    let cList = [{
      text: d.title,
      id: d.key * 1,
      no: d.no,
      name: d.title,
    }];
    const getData = function (dc) {
      if (dc.children && dc.children.length > 0) {
        dc.children.map(m => {
          if (m.children && m.children.length > 0) {
            getData(m, m.title);
          }
          else {
            cList.push({
              text: m.title,
              id: m.key * 1,
              no: m.no,
              name: m.title,
            })
          }
        });
      }
    };
    getData(d);
    return cList;
  },

  getDepData(d = [], orgId = 0) {
    const depItems = d.filter(m => m.parentId * 1 === orgId * 1);
    this.setData({ depItems });
  },

  getCategoryData(d) {
    let data = [];
    d.map(m => {
      data.push({
        text: m.title,
        id: m.key,
        disabled: false,
        children: this.getCategoryChildren(m),
      });
      return m.key;
    })
    this.setData({ categoryItems: data });
  },

  getCategoryChildren(d) {
    let cList = [];
    const getData = function (dc, parentStr) {
      if (dc.children && dc.children.length > 0) {
        dc.children.map(m => {
          if (m.children && m.children.length > 0) {
            getData(m, m.title);
          }
          else {
            cList.push({
              text: parentStr ? parentStr + '-' + m.title : m.title,
              id: m.key * 1,
              no: m.no,
              name: m.title,
            })
          }
        });
      }
    };
    getData(d, '');
    return cList;
  },

  onOrgClickNav({ detail = {} }) {
    this.setData({
      orgMainActiveIndex: detail.index || 0
    });
  },

  onOrgClickItem({ detail = {} }) {
    const { inventoryDetail } = this.data;
    const orgActiveId = this.data.orgActiveId === detail.id ? null : detail.id;
    inventoryDetail.OrganizationId = orgActiveId;
    inventoryDetail.OrganizationName = detail.name;
    inventoryDetail.UserDepartmentId = 0;
    inventoryDetail.UserDepartmentName = "";
    inventoryDetail.ManageDepartmentId = 0;
    inventoryDetail.ManageDepartmentName = "";
    this.getDepData(inventoryDetail.Departments, orgActiveId);
    this.setData({ orgActiveId, inventoryDetail, showOrg: false });
  },

  onCategoryClickNav({ detail = {} }) {
    console.log(detail);
    this.setData({
      categoryMainActiveIndex: detail.index || 0
    });
  },

  onCategoryClickItem({ detail = {} }) {
    const { categoryMainActiveIndex, categoryItems, inventoryDetail } = this.data;
    const categoryActiveId = this.data.categoryActiveId === detail.id ? null : detail.id;
    const category = categoryItems[categoryMainActiveIndex];
    if (category) {
      const asset = category.children ? category.children.filter(m => m.id === categoryActiveId)[0] : null;
      if (asset) {
        inventoryDetail.AssetsCategoryName = category.text;
        inventoryDetail.AssetsCategoryId = asset.id;
        inventoryDetail.AssetsEncoding = asset.no;
        inventoryDetail.AssetsName = asset.name;
        this.setData({ categoryActiveId, inventoryDetail, showCategory: false });
      }
    }
  },

  onCategoryChange({ detail = '' }) {
    this.setData({ categoryValue: detail });
  },

  onCategorySearch() {
    const { categoryValue, inventoryDetail: { Categorys } } = this.data;
    let categoryItems = [];
    Categorys.map(m => {
      categoryItems.push({
        text: m.title,
        id: m.key,
        disabled: false,
        children: this.getCategoryChildren(m),
      });
      return m.key;
    })
    const searchItem = categoryItems.filter(m => m.children && m.children.filter(c => c.text.indexOf(categoryValue) >= 0).length > 0);
    searchItem.map(m => {
      m.children = m.children.filter(c => c.text.indexOf(categoryValue) >= 0);
    })
    this.setData({ categoryItems: searchItem });
  }

})